package com.example.rule.engine;

import com.example.rule.entity.po.RulePO;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AviatorEngine extends BaseEngine {
    @Override
    public double execute(List<RulePO> tasks) {
        int successCount = 0;

        for (RulePO task : tasks) {
            try {
                Expression compiledExp = AviatorEvaluator.compile(task.getExpression());
                Map<String, Object> env = new HashMap<>();
                env.put("data", task.getData());
                Object result = compiledExp.execute(env);
                
                if (result instanceof Boolean && Boolean.TRUE.equals(result)) {
                    successCount++;
                }
            } catch (Exception e) {
                // 可记录日志或跳过异常表达式
                System.err.println("Aviator规则执行异常: " + e.getMessage());
            }
        }

        return tasks.isEmpty() ? 0.0 : (double) successCount / tasks.size();
    }
}
